package com.scienjus.of;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class OfUtil {
	public static String OF_URL = "http://A1239037.api2.ofpay.com/";
	public static String OF_ID = "A1239037";
	public static String OF_PASSWORD = "41390ebd8e6a714e8ce85c4eabfac3f5";
	public static String CHARSET_GBK = "GBK";
	public static String CHARSET_UTF = "UTF-8";

	public static double getBalance() {
		String url = OF_URL + "queryuserinfo.do?userid=" + OF_ID + "&userpws=" + OF_PASSWORD + "&version=6.0";
		String msg = doGet(url, CHARSET_GBK, CHARSET_GBK);
		if (null != msg) {
			try {
				SAXReader reader = new SAXReader();
				reader.setEncoding(CHARSET_UTF);
				Document document = reader.read(new ByteArrayInputStream(msg.getBytes(CHARSET_UTF)));
				Element root = document.getRootElement();
				String code = root.elementText("retcode");
				String balance = root.elementText("ret_leftcredit");
				String userId = root.elementText("userid");
				if ("1".equals(code) && OF_ID.equals(userId)) {
					return Double.parseDouble(balance);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return -9999;
	}

	public static String doGet(String url, String connectionFormat, String streamFormat) {
		if (null != url) {
			try {
				URL urlGet = new URL(url);
				// 打开和URL之间的连接
				URLConnection connection = urlGet.openConnection();
				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				// 建立实际的连接
				connection.connect();
				InputStream is = connection.getInputStream();
				BufferedReader in = new BufferedReader(new InputStreamReader(is, streamFormat));
				StringBuffer buffer = new StringBuffer();
				String line = "";
				while ((line = in.readLine()) != null) {
					buffer.append(line);
				}
				is.close();
				System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+">>查询余额返回信息："+buffer.toString()+"<< 请勿关闭此窗口！！！");
				return buffer.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	public static void main(String[] args) {
		getBalance();
	}
}
